import store from '@/dvadmin/store';
// 判断字符串是否为JSON格式
function isJSON(str) {
	if (typeof str == 'string') {
		try {
			var obj = JSON.parse(str);
			return typeof obj == 'object' && obj;
		} catch (e) {
			// console.log('error：'+str+'!!!'+e);
			return false;
		}
	}
	// console.log('It is not a string!')
}


class WebSocketClass {
	constructor(url, time=5000) {
		this.url = url
		this.data = null
		this.isOpenSocket = false
		// 心跳检测
		this.timeout = time
		this.heartbeat = null
		try {
			return this.connectSocketInit()
		} catch (e) {
			this.isOpenSocket = false
			this.reconnect();
		}
	}

	//连接websocket
	connectSocketInit() {
		this.socketTask = uni.connectSocket({
			url: this.url,
			complete: ()=> {}
		})
		console.log(this.socketTask)
		this.socketTask.onOpen((res) => {
			clearTimeout(this.heartbeat);
			this.isOpenSocket = true
			this.start();
			this.socketTask.onMessage((res) => {
				//接收消息
				const {data} = res
				//判断是否为json格式
				if(isJSON(data)){
					const result = JSON.parse(data)
					console.log(result)
					const { unread } = result
					  store.dispatch('setUnreadMsg', unread || 0)
				}else{
					uni.showToast({
						icon:'error',
						title:"数据格式不正确"
					})
				}
			})
		})

		this.socketTask.onClose(() => {
			this.isOpenSocket = false;
			this.reconnect();
		})
	}

	//发送消息
	send(data) {
		this.socketTask.send({
			data,
		})
	}
	//开启心跳检测
	start() {
		this.heartbeat = setTimeout(() => {
			this.data = {
				value: 'xx'
			}
			this.send(JSON.stringify(this.data));
		}, this.timeout)
	}
	// 重新连接
	reconnect() {
		clearInterval(this.heartbeat)
		if (!this.isOpenSocket) {
			setTimeout(() => {
				this.connectSocketInit();
			}, 3000)
		}
	}

	//关闭websocket
	closeSocket(){
		this.socketTask.onClose()
	}
}
export default WebSocketClass;
